import React from 'react';
import { SortableContainer, SortableElement, arrayMove } from 'react-sortable-hoc';

import AppMenu from './AppMenu';

const SortableItem = SortableElement(({ _index, item }) => <AppMenu ecId={`${this && this.props && this.props.ecId || ''}_AppMenu@x0iaqm`} key={_index} index={_index} item={item} />);

const SortableList = SortableContainer(({ items, start }) => (
        <div className="e9desktop-content-menus">
            {items.map((item, index) => <SortableItem ecId={`${this && this.props && this.props.ecId || ''}_SortableItem@jq4ohs@${index}`} key={`item-${index}`} index={start + index} _index={start + index} item={item} />)}
        </div>
    ));

class DragSort extends React.Component {
    constructor(props) {
        super(props);
        this.onSortEnd = this.onSortEnd.bind(this);
    }

    onSortEnd({ oldIndex, newIndex }) {
        const { datas, items, start, num, onSort } = this.props;
        const _datas = arrayMove(items, oldIndex, newIndex);
        const __datas = _datas.filter((item) => {
            if (item) return item;
        });
        if (datas) {
            datas.splice(start, num, ...__datas);
            onSort({ datas });
        } else {
            onSort({ datas: __datas });
        }
    }

    render() {
        const { isSetting, items, start = 0, shouldCancelStart } = this.props;

        if (isSetting) {
            return <SortableList ecId={`${this && this.props && this.props.ecId || ''}_SortableList@97pyym`} axis={'xy'} items={items} start={start} shouldCancelStart={shouldCancelStart} onSortEnd={this.onSortEnd} />;
        }

        return (
            <div className="e9desktop-content-menus">
                {items.map((item, index) => <AppMenu ecId={`${this && this.props && this.props.ecId || ''}_AppMenu@b84zix@${index}`} key={`item-${index}`} index={start + index} item={item} />)}
            </div>
        );
    }
}

export default DragSort;
